package com.rf.richfitwheel.workflow.listener;

import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.workflow.conf.WorkflowContants;

import com.rf.richfitwheel.workflow.entity.WorkflowMsgVo;
import com.rf.richfitwheel.workflow.rabbitmq.WorkflowSender;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component("processStartListener")
public class ProcessStartListener implements ExecutionListener {
    @Autowired
    private WorkflowSender workflowSender;
    @Autowired
    protected RepositoryService repositoryService;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        /*System.out.println("流程启动");
        System.out.println("EventName:" + delegateExecution.getEventName());
        System.out.println("ProcessDefinitionId:" + delegateExecution.getProcessDefinitionId());
        System.out.println("ProcessInstanceId:" + delegateExecution.getProcessInstanceId());
        System.out.println("=======");*/
        ProcessDefinition processDefinition = this.repositoryService.getProcessDefinition(delegateExecution.getProcessDefinitionId());
        WorkflowMsgVo workflowMsgVo = new WorkflowMsgVo();//消息队列信息
        workflowMsgVo.setUserVO(UserUtil.getUser());
        Map<String, Object> variables = delegateExecution.getVariables();
        variables.put("processInstanceState", WorkflowContants.ProcessInstanceState.RUN.getValue());//流程运行中
        String moduleType = (String) variables.get("moduleType");//模块类型
        String queueName = (String) variables.get("queueName");//消息队列名
        if (StringUtils.isBlank(queueName)) {
            log.warn("ID为{}的流程消息队列名称是空的", delegateExecution.getProcessInstanceId());
        }
        String startUserId = (String) variables.get("startUserId");//发起人
        workflowMsgVo.setModuleType(moduleType);
        workflowMsgVo.setQueueName(queueName);
        workflowMsgVo.setEventName(WorkflowContants.EVENTNAME_PROCESS_START);
        workflowMsgVo.setProcessDefinitionId(processDefinition.getId());
        workflowMsgVo.setProcessDefinitionKey(processDefinition.getKey());
        workflowMsgVo.setProcessDefinitionName(processDefinition.getName());
        workflowMsgVo.setProcessInstanceId(delegateExecution.getProcessInstanceId());
        workflowMsgVo.setStartUserId(startUserId);
        workflowMsgVo.setVariables(variables);
        workflowSender.sendWorkflowMsg(workflowMsgVo);//向消息队列发送消息
    }
}